<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1050px"
      draggable
      @close="closeDialog"
      destroy-on-close
      align-center
      class="maxhDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="115px"
        v-show="!props.isReadonly"
      >
        <!-- <h4 class="mb-[20px] mt-[0px]">计划信息</h4> -->
        <div class="form_1">
          <el-row>
            <el-col :span="8">
              <el-form-item label="计划编号" prop="planNo">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planNo"
                  placeholder="请输入计划编号"
                  clearable
                />
                <span v-else>{{ formData.planNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划名称" prop="planName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planName"
                  placeholder="请输入计划名称"
                  clearable
                />
                <span v-else>{{ formData.planName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="点检周期" prop="taskPeriod">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.taskPeriod"
                  placeholder="请输入点检周期"
                  clearable
                  style="width: 100%"
                >
                  <template #append>
                    <el-select
                      v-model="formData.taskPeriodUnit"
                      placeholder="单位"
                      style="width: 65px"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'TaskPeriodUnit'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="Number(item.value)"
                      />
                    </el-select>
                  </template>
                </el-input>
                <span v-else>{{ formData.taskPeriod }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="点检时间" prop="planInspectionTime">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planInspectionTime"
                  placeholder="请输入点检时间"
                >
                  <template #append>小时</template>
                </el-input>

                <span v-else>{{ formData.planInspectionTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划起始日期" prop="planStartDate">
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.planStartDate"
                  type="date"
                  :rules="rules.planStartDate"
                  placeholder="请选择计划起始日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
                <span v-else>{{ formData.planStartDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划截止日期" prop="planEndDate">
                <el-date-picker
                  v-if="!props.isReadonly"
                  v-model="formData.planEndDate"
                  type="date"
                  :rules="rules.planEndDate"
                  placeholder="请选择计划截止日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
                <span v-else>{{ formData.planEndDate }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="16">
              <el-form-item
                label="备注"
                prop="remarks"
                style="width: 97.5% !important"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                  style="width: 100%"
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否启用" prop="enabled">
                <template v-if="!props.isReadonly">
                  <el-radio-group v-model="formData.enabled">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
                </template>
                <span v-else>{{
                  dictionaryStore.filterDictName("YesNo", formData.enabled)
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- <h4 class="mb-[20px] mt-[20px]">点检路线</h4> -->
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <div class="mb-[10px] mt-[20px] text-[15px]">设备列表</div>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>

        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
            show-overflow-tooltip
          >
            <!-- <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            /> -->

            <el-table-column label="设备编码" props="assetCode" min-width="100">
              <template #default="{ $index, row }">
                <span>{{ row.assetCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="设备名称" props="assetName" min-width="100">
              <template #default="{ $index, row }">
                <span>{{ row.assetName }}</span>
              </template>
            </el-table-column>
            <!-- :rules="rules.sonsopStandardId" -->
            <el-table-column
              label="点检人员"
              props="taskPersonIds"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.taskPersonIds'"
                  label-width="0"
                  :rules="rules.taskPersonIds"
                >
                  <SelectPerson
                    :key="$index"
                    :isMultiple="false"
                    :maxCollapseTags="1"
                    :showSelectPerson="filterTaskPerson(row)"
                    @get-person="
                      (id, object) => getDayPerson(id, object, $index)
                    "
                    :width="'100%'"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="点检标准"
              props="sopStandardId"
              min-width="150"
              align="center"
              style="padding-top: 15px"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.sopStandardId'"
                  :rules="rules.sopStandardId"
                  label-width="0"
                >
                  <el-select
                    v-model="row.sopStandardId"
                    placeholder="请选择点检标准"
                    clearable
                    filterable
                    style="width: 100%"
                    @change="(e) => handleChange(e, $index)"
                  >
                    <el-option
                      v-for="item in standardList"
                      :key="item.id"
                      :label="item.standardName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- <h4 class="mb-[13px] mt-[20px]">附件</h4>
        <el-row class="ml-[15px]">
          <el-form-item>
            <CommonUploadFile
              :isRead="props.isReadonly"
              :files="formData.assetPhotos"
              @update-files="updateFormFiles"
            />
          </el-form-item>
        </el-row> -->
      </el-form>
      <!-- <h4 class="mb-[20px] mt-[0px]" v-show="props.isReadonly">计划信息</h4> -->
      <el-descriptions
        class="margin-top"
        title=""
        :column="3"
        border
        v-show="props.isReadonly"
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划编号</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.planNo }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划名称</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.planName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">点检周期</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.taskPeriod
            }}{{
              dictionaryStore.filterDictName(
                "TaskPeriodUnit",
                formData.taskPeriodUnit
              )
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">点检时间(小时)</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.planInspectionTime }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划起始日期</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{
              formData.planStartDate
                ? dayjs(formData.planStartDate).format("YYYY-MM-DD")
                : ""
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划截止日期</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{
              formData.planStartDate
                ? dayjs(formData.planEndDate).format("YYYY-MM-DD")
                : ""
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">是否启用</div>
          </template>
          <el-tag v-if="formData.enabled === 1" type="">启用</el-tag>
          <el-tag v-else type="info">停用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <div class="mb-[10px] mt-[20px] text-[15px]" v-show="props.isReadonly">
        设备列表
      </div>
      <el-table
        :data="formData.details"
        style="width: 100%"
        :key="Math.random"
        v-show="props.isReadonly"
        max-height="300px"
        show-overflow-tooltip
        border
      >
        <el-table-column
          label="设备编码"
          props="assetCode"
          min-width="100"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.assetCode }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="设备名称"
          props="assetName"
          min-width="150"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.assetName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="点检人员"
          props="taskPersonNames"
          min-width="100"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.taskPersonNames }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="点检标准"
          props="sopStandardId"
          min-width="150"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ filterStandardName(row.sopStandardId) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- <h4 class="mb-[20px] mt-[20px]" v-show="props.isReadonly">附件</h4>
      <el-row class="ml-[15px]">
        <CommonUploadFile
          v-show="props.isReadonly"
          :showText="formData.assetPhotos?.length > 0"
          :isRead="props.isReadonly"
          :files="formData.assetPhotos"
          @update-files="updateFormFiles"
        />
      </el-row> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-if="formData.id"
            @click="openBuildDialog(formData)"
            >生成点检单</el-button
          >
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit('')"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 设备选择 -->
    <!-- <selectEquipDialog-mdm
      v-model:visible="selectDialog.visible"
      :data="breakList"
      @echo-info="changeVisible"
    /> -->
    <eaminspectionplan-select
      v-model:visible="selectDialog.visible"
      :data="breakList"
      @echo-info="changeVisible"
    />
    <!-- 生成点检单 -->
    <equAccuracyInspectionPlan-build
      v-model:visible="buildDialog.visible"
      :id="buildDialog.id"
      @echo-info="changeBuildVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { validateNumber } from "@/utils/commonHooks";
import dayjs from "dayjs";

defineOptions({
  name: "EAMEAMINSPECTIONPLANADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
    if (newVal === true) {
      getStandardList();
    }
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive(<any>{
  id: "",
  version: "",
  assetKind: "1",
  planNo: "",
  planName: "",
  sopTypeId: "",
  taskPeriod: "",
  taskPeriodUnit: 1,
  planStartDate: "",
  planEndDate: "",
  planInspectionTime: "",
  enabled: 1,
  remarks: "",
  createTime: "",
  // 附件上传
  assetPhotos: [],
  // 详情列表
  details: [],
});

/** rules规则 */
const rules = reactive({
  planNo: [
    { required: true, message: "请输入计划编号", trigger: "blur" },
    { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
  ],
  planName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符" },
    { required: true, message: "请输入计划名称", trigger: "blur" },
  ],
  assetName: [{ required: true, message: "请选择设备", trigger: "change" }],
  taskPeriod: [
    { required: true, message: "请输入点检周期", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  planStartDate: [
    { required: true, message: "请选择计划起始时间", trigger: "change" },
    {
      validator: validatorStartData,
      trigger: "change",
    },
  ],
  planEndDate: [
    { required: true, message: "请选择计划截止时间", trigger: "change" },
    {
      validator: validatorEndData,
      trigger: "change",
    },
  ],
  planInspectionTime: [
    { required: true, message: "请填写点检时间", trigger: "change" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  taskPersonIds: [
    { required: true, message: "请选择点检人员", trigger: "change" },
  ],
  sopStandardId: [
    { required: true, message: "请选择点检标准", trigger: "change" },
  ],
});

function validatorStartData(rule, value, callback: (a?: any) => {}) {
  console.log(value);

  if (!value) {
    callback(new Error("请选择计划起始时间"));
  } else {
    if (formData.planEndDate && value > formData.planEndDate) {
      callback(new Error("计划起始时间不能大于计划截止时间"));
    } else {
      return true;
    }
  }
}

function validatorEndData(rule, value, callback: (a?: any) => {}) {
  console.log(value);

  if (!value) {
    callback(new Error("请选择计划截止时间"));
  } else {
    if (formData.planStartDate && value < formData.planStartDate) {
      callback(new Error("计划截止时间不能小于计划起始时间"));
    } else {
      return true;
    }
  }
}

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

/** 添加行 */
const handleAdd = () => {
  selectDialog.visible = true;
  if (formData.details.length > 0) {
    getBreakList();
  }
};

const selectDialog = reactive({
  visible: false,
  data: [],
});
const changeVisible = (val: any) => {
  console.log("breakList.value", formData.details);
  const elderDetails = JSON.parse(JSON.stringify(formData.details ?? []));

  if (val && val.length) {
    formData.details = [];
    // console.log("返回的数据", val);
    val?.forEach((item: any) => {
      const current = elderDetails.filter(
        (self) => self.assetId === item.id
      )?.[0];
      if (current) {
        formData.details.push(current);
      } else {
        formData.details.push({
          assetId: item.id,
          assetCode: item.assetCode,
          assetName: item.assetName,
        });
      }
    });
  } else {
    formData.details = [];
  }
  // selectDialog.visible = val;
};

// 点击角色下拉框 进行id赋值
const handleChange = (e, index) => {
  if (e) {
    const current =
      standardList.value.filter((item: any) => item.id === e)[0] || {};
    formData.details[index].sopStandardCode = current.standardCode || "";
    formData.details[index].sopStandardId = current.id || "";
  } else {
    formData.details[index].sopStandardCode = "";
    formData.details[index].sopStandardId = "";
  }
};

// 新增完返回的数据用于显示选择器
const breakList = ref(<any>[]);
const getBreakList = () => {
  breakList.value = [];
  formData.details.forEach((item: any) => {
    if (item.assetId) {
      breakList.value.push({
        id: item.assetId,
        assetCode: item.assetCode,
        assetName: item.assetName,
      });
    }
  });
};
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
    formRef.value.clearValidate();
  }

  // formData.details = [JSON.parse(JSON.stringify(details))];
  formData.details = [];
  formData.id = "";
  formData.version = "";
  formData.assetKind = "";
  formData.planNo = "";
  formData.planName = "";
  formData.sopTypeId = "";
  formData.taskPeriod = "";
  formData.taskPeriodUnit = 1;
  formData.planStartDate = "";
  formData.planEndDate = "";
  formData.planInspectionTime = 0;
  formData.enabled = 1;
  formData.remarks = "";
  formData.createTime = "";
  formData.assetPhotos = [];
  breakList.value = [];
}

function getDayPerson(Ids: string[], Objects: any, index: number) {
  console.log("getDayPerson", Ids, Objects, index);

  formData.details[index].taskPersonIds = Objects[0]?.id || "";
  formData.details[index].taskPersonNames = Objects[0]?.firstName || "";
}

function filterTaskPerson(row: any) {
  return row?.taskPersonIds
    ? [
        {
          id: row.taskPersonIds,
          firstName: row.taskPersonNames,
        },
      ]
    : [];
}

const loading = ref(false);

/** 点检计划保存提交 */
function handleSubmit(params = "") {
  console.log("formData", formData);
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      console.log("formData", formData);

      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/equPrecisionCheckPlan/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      if (params === "build") {
        buildDialog.visible = true;
        buildDialog.id = formData.id;
      } else {
        ElMessage.success(text + `成功`);
        closeDialog();
        emit("reset-table", formData.id);
        isValidated.value = false;
      }
    } else {
      isValidated.value = true;
    }
  });
}

function changeBuildVisible() {
  closeDialog();
  emit("reset-table", formData.id);
  isValidated.value = false;
}

// 标准作业列表
const standardList = ref(<any>[]);
async function getStandardList() {
  const data = await request({
    url: "/eam/eamsopstandard/getList",
    method: "post",
    data: { sopTypeCode: "EquipPrecisionInspect" },
  }).finally(() => {});
  // console.log("getStandardList", data.data);
  standardList.value = data.data;
}

function filterStandardName(id: string) {
  if (id) {
    const current =
      standardList.value?.filter((item: any) => item?.id === id)[0] ?? {};
    return current?.standardName || "";
  } else {
    return "";
  }
}

// 定义生成点检单弹窗
const buildDialog = reactive<DialogOption>({
  visible: false,
  id: "",
});

// 打开生成点检单弹窗
function openBuildDialog(roleObj?: any) {
  if (roleObj.details && roleObj.details.length) {
    handleSubmit("build");
  } else {
    ElMessage.error("请先完善设备列表信息");
  }
}

onMounted(() => {});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.form_1 {
  :deep(.el-form-item) {
    width: 95% !important;
  }
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
  :deep(.el-scrollbar__wrap) {
    max-height: 290px;
    overflow-y: auto;
  }
}

.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-dialog .formTable .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable .el-table) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }

  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

// :deep(.el-dialog .el-dialog__body) {
//   overflow-y: auto;
//   height: 65vh;
// }

// :deep(.search-container .el-input.el-input--default.el-input--suffix) {
//   // 固定宽度
//   width: 190px !important;
// }

// :deep(.search-container .el-form-item--default .el-form-item__label) {
//   // 固定宽度
//   justify-content: end;
// }

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}

:deep(.maxhDialog .el-dialog__body) {
  max-height: 75vh;
  overflow-y: auto;
  padding: 20px;
}
:deep(.el-tag__content .el-select__tags-text) {
  max-width: 100% !important;
}
</style>
